package com.hnkjzyxy.ab.config;

import com.hnkjzyxy.ab.utils.SmartLockQuartz;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {

    @Autowired
    private QuartzJobFactory quartzJobFactory; // 注入自定义JobFactory

    // 创建JobDetail
    public JobDetail createJobDetail(int lockId, Integer userId) {
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("lockId", lockId);
        dataMap.put("userId", userId);

        return JobBuilder.newJob(SmartLockQuartz.class)
                .withIdentity("smartLockJob_" + lockId, "smartLockGroup")
                .setJobData(dataMap)
                .storeDurably()
                .build();
    }

    // 创建Trigger，这里使用SimpleTrigger作为示例
    public Trigger createTrigger(JobDetail jobDetail) {
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(jobDetail.getKey().getName() + "_trigger", "smartLockTriggerGroup")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withRepeatCount(0)) // 只执行一次
                .build();
    }

    // 创建CronTrigger（支持每周特定天数和时间，带重复次数控制）
    public Trigger createCronTrigger(JobDetail jobDetail, String cronExpression, Integer repeatCount) {
        // 获取JobDataMap（之前的代码漏了这行，导致jobDataMap无法引用）
        JobDataMap jobDataMap = jobDetail.getJobDataMap();

        // 如果设置了重复次数（>=0），存储到JobDataMap中
        if (repeatCount != null && repeatCount >= 0) {
            // 存储最大执行次数（总重复次数）
            jobDataMap.put("maxExecutionCount", repeatCount);
            // 初始化当前执行次数（从0开始计数）
            jobDataMap.put("currentExecutionCount", 0);
        }

        return TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(jobDetail.getKey().getName() + "_cron_trigger", "smartLockTriggerGroup")
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)
                        .withMisfireHandlingInstructionDoNothing())
                .build();
    }

    // 重载方法：不指定重复次数时默认无限重复
    public Trigger createCronTrigger(JobDetail jobDetail, String cronExpression) {
        return createCronTrigger(jobDetail, cronExpression, null);
    }

    // 生成每周特定天数和时间的Cron表达式
    public String generateWeeklyCronExpression(int hour, int minute, int[] daysOfWeek) {
        // 转换星期几格式（前端传递0-6代表周一到周日，转为Quartz的2-7,1）
        StringBuilder days = new StringBuilder();
        for (int day : daysOfWeek) {
            int quartzDay = day == 6 ? 1 : day + 2; // Quartz中1=周日，2=周一...7=周六
            days.append(quartzDay).append(",");
        }
        if (days.length() > 0) days.deleteCharAt(days.length() - 1); // 移除最后一个逗号

        // 确保时分在有效范围内
        hour = Math.max(0, Math.min(23, hour));
        minute = Math.max(0, Math.min(59, minute));

        return String.format("0 %d %d ? * %s", minute, hour, days.toString());
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(quartzJobFactory); // 设置自定义JobFactory
        return schedulerFactoryBean;
    }
}